﻿Imports System.ComponentModel
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Siemens
Public Class frmHB_PT
    Private g_szInitFileName As String
    Private logfile As ILogNet
    Private plc As SiemensS7Net
    Private objDB As New clsEquit_HB_PT
    Private Power_Inserted As Boolean

    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub frmHB_PT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If

        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\PT.ini"
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        connectDB()

        Dim plcIP As String = GetIniFile("IP", "PLC", "", Me.g_szInitFileName)

        '读PLC
        plc = New SiemensS7Net(SiemensPLCS.S200Smart)
        With plc
            .IpAddress = plcIP
            .Port = 102
            .SetPersistentConnection()
        End With

        readPLC()
        Timer1.Interval = 3 * 60 * 1000
        Timer1.Start()
    End Sub
    Public Sub connectDB()
        'イニシャルファイル情報取得

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Private Sub readPLC()
        Dim _en As New en_equit_hb_PT_item
        dgvErr.DataSource = Nothing
        dgvErr.Refresh()


        'Dim ping = New Net.NetworkInformation.Ping()
        'Dim pingResult1F As Net.NetworkInformation.PingReply = ping.Send(plcIP)
        'Try
        '    If pingResult1F.Status <> Net.NetworkInformation.IPStatus.Success Then
        '        With _en
        '            .save_time = Now                                   ' 保存时间
        '            .power_on = False           ' 开关机状态
        '            If .power_on = False And Power_Inserted = True Then
        '                Dim dt As DataTable = objDB.selectErrorAll()
        '                If dt.Rows.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    dgvErr.DataSource = dt
        '                End If

        '                Exit Sub
        '            ElseIf .power_on = False And Power_Inserted = False Then
        '                Power_Inserted = True
        '            End If

        '            If .power_on = False Then
        '                objDB.insert(_en)
        '                Dim dt As DataTable = objDB.selectErrorAll()
        '                If dt.Rows.Count = 0 Then
        '                    Exit Sub
        '                Else
        '                    dgvErr.DataSource = dt
        '                End If
        '                Exit Sub
        '            End If
        '        End With
        '    End If
        'Catch ex As Exception

        'End Try
        Dim dtData As DataTable = objDB.selectData()
        dgvData.DataSource = dtData

        Dim dt As DataTable = objDB.selectErrorAll()
        If dt.Rows.Count > 0 Then
            dt.Columns.Add("value")
        End If
        Try
            With _en
                .save_time = Now                                   ' 保存时间
                ' 开关机状态
                'Q0.6	BOOL	RTO风机 运行中继
                If plc.ReadBool("Q0.6").IsSuccess Then
                    .power_on = plc.ReadBool("Q0.6").Content
                Else
                    .power_on = False
                End If
                If .power_on = True Then ' 开关机状态
                    For Each _dr As DataRow In dt.Rows

                        Dim err As Boolean = plc.ReadBool(_dr("plc_address")).Content
                        _dr("value") = err
                        If err Then
                            objDB.insertError(_dr("note"))
                        End If
                    Next
                End If
                dgvErr.DataSource = dt
                '保存数据库


                If .power_on = False And Power_Inserted = True Then
                    Exit Sub
                ElseIf .power_on = False And Power_Inserted = False Then
                    Power_Inserted = True
                End If
                If .power_on = False Then
                    objDB.insert(_en)
                    Exit Sub
                End If
                ',纸质的A中就是电子表格里的A上。纸质的A上应该是电子表格里的RTO燃烧室左温度
                'VD3004	real	读取值 T02 RTO燃烧室左温度
                'VD3016	real	读取值 T05 RTO-A蓄热室上温度
                'VD3020	real	读取值 T06 RTO-A蓄热室下温度
                .a_up = plc.ReadFloat("VD3004").Content
                .a_mid = plc.ReadFloat("VD3016").Content '■
                .a_dn = plc.ReadFloat("VD3020").Content

                'VD3008	real	读取值 T03 RTO燃烧室中间温度
                'VD3024	real	读取值 T07 RTO-B蓄热室上温度
                'VD3028	real	读取值 T08 RTO-B蓄热室下温度
                .b_up = plc.ReadFloat("VD3008").Content
                .b_mid = plc.ReadFloat("VD3024").Content '■
                .b_dn = plc.ReadFloat("VD3028").Content

                'VD3012	real	读取值 T04 RTO燃烧室右温度
                'VD3032	real	读取值 T09 RTO-C蓄热室上温度
                'VD3036	real	读取值 T10 RTO-C蓄热室下温度
                .c_up = plc.ReadFloat("VD3012").Content
                .c_mid = plc.ReadFloat("VD3032").Content '■
                .c_dn = plc.ReadFloat("VD3036").Content

                .room_avg = (plc.ReadFloat("VD3004").Content + plc.ReadFloat("VD3008").Content + plc.ReadFloat("VD3012").Content) / 3

                .fq_in = plc.ReadFloat("VD3000").Content
                .fq_out = plc.ReadFloat("VD3040").Content

                'VD3048	real	读取值 P02 RTO炉膛压力变送器
                .room_pa = plc.ReadFloat("VD3048").Content

                'VD3044	real	读取值 P01 废气进口压力变送器
                .rto_pa = plc.ReadFloat("VD3044").Content

                .po3_pa = plc.ReadFloat("VD3052").Content
                .po4_pa = plc.ReadFloat("VD3056").Content
                .po5_pa = plc.ReadFloat("VD3060").Content

                '风机过滤网情况，应该指的是震安肉眼观测的，风机吸风口与大气接触的过滤网。电气没有检测
                .filter_status = 0 'plc.ReadBool("?").Content  '■ ' 风机过滤网状态:0为正常，1为异常
            End With
            Power_Inserted = False
            objDB.insert(_en)
        Catch ex As Exception
            logfile.WriteError("Connect Failed:" & ex.Message)
        End Try

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        readPLC()
    End Sub

    Private Sub 关闭ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 关闭ToolStripMenuItem.Click
        If MsgBox("如关闭系统，则停止喷涂设备监控！" & vbCrLf & "确定要关闭吗？", 4, Me.Text) = MsgBoxResult.Yes Then
            RemoveHandler Me.Closing, AddressOf frmHB_PT_Closing
            NotifyIcon1.Dispose()
            Timer1.Stop()
            Close()
        End If
    End Sub

    Private Sub frmHB_PT_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        Me.Hide()
        e.Cancel = True
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Me.Show()
    End Sub
End Class
Public Class clsEquit_HB_PT
    Public Function selectErrorAll() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_pt_error_address "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectErrorAll = New DataTable
        Else
            selectErrorAll = rtn
        End If
        Return rtn
    End Function
    Public Function selectData() As DataTable
        Dim szSql As String = ""
        Dim rtn As DataTable

        szSql &= "SELECT * FROM sf.b_equip_info_hb_pt order by save_time DESC "
        rtn = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(rtn) Then
            selectData = New DataTable
        Else
            selectData = rtn
        End If
        Return rtn
    End Function
    Public Function insertError(errorInfo As String) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer

        Try
            szSql = "INSERT INTO sf.b_equip_info_hb_pt_error(save_time , error) VALUES (?,?)"
            rtn = DBacs.ExecuteUpdateSql(szSql, -1, Now, errorInfo)

        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function
    Public Function insert(_en As en_equit_hb_PT_item) As Integer
        Dim szSql As String = String.Empty
        Dim rtn As Integer

        Try
            szSql &= "INSERT INTO sf.b_equip_info_hb_pt( save_time , power_on , a_up , a_mid , a_dn , b_up , b_mid , b_dn , c_up , c_mid , c_dn , room_avg , fq_in , fq_out , room_pa , rto_pa , po3_pa , po4_pa , po5_pa , filter_status ) VALUES "
            szSql &= " ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ) "

            With _en
                rtn = DBacs.ExecuteUpdateSql(szSql, -1, .save_time, .power_on, .a_up, .a_mid, .a_dn, .b_up, .b_mid, .b_dn, .c_up, .c_mid, .c_dn, .room_avg, .fq_in, .fq_out, .room_pa, .rto_pa, .po3_pa, .po4_pa, .po5_pa, .filter_status)
            End With
        Catch ex As Exception
            rtn = -2
        End Try
        Return rtn
    End Function
End Class
Public Class en_equit_hb_PT_item
    Public save_time As DateTime  ' 保存时间 
    Public power_on As Boolean    ' 开关机状态 
    Public a_up As Double   ' A上 
    Public a_mid As Double  ' A中 
    Public a_dn As Double   ' A下 
    Public b_up As Double   ' B上 
    Public b_mid As Double  ' B中 
    Public b_dn As Double   ' B下 
    Public c_up As Double   ' C上 
    Public c_mid As Double  ' C中 
    Public c_dn As Double   ' C下 
    Public room_avg As Double  ' 燃烧室平均温度 
    Public fq_in As Double     ' 废气进口温度 
    Public fq_out As Double    ' 废气出口温度 
    Public room_pa As Double   ' 燃烧室压力（Pa） 
    Public rto_pa As Double    ' RTO压力（Pa） 
    Public po3_pa As Double    ' PO3压力（Pa） 
    Public po4_pa As Double    ' PO4压力（Pa） 
    Public po5_pa As Double    ' PO5压力（Pa） 
    Public filter_status As Integer  ' 风机过滤网状态 
End Class